<template>
	<view>
		<action-bar backTitle="返回" title="记点什么吧"></action-bar>
		<view class="bg-white">
			<view class="grid col-4 text-center padding" style="height: 67rpx;margin-bottom: 40rpx;">
				<view>
					<button @click="changeRecordType(false)" class="cu-btn " :class="recordType ? '' : 'bg-green'">收入</button>
				</view>
				<view>
					<button @click="changeRecordType(true)" class="cu-btn" :class="recordType ? 'bg-red' : ''">支出</button>
				</view>
			</view>
			
			<scroll-view scroll-y="true" :style="'height:' + scrollHeight + 'rpx'" :scroll-into-view="curSelectItem">
				<!-- 支出 -->
				<view v-show="recordType" class="grid col-4 text-center">
					<view :id="'_' + item.id"
						  v-for="(item, index) in outcome_icons"
						  :class="curSelectItemId == item.id ? 'jump-animation':''"
						  @click="record(item.id, item.name)">
						<view class="cu-avatar round margin-top-xl"
							  :class="curSelectItemId == item.id ? 'select-icon':''"
							  style="background-color: #FFFFFF !important"
							  :style="'background-image: url(' + base64_header + item.path + ')'">
						</view>
						<view class="text-sm" v-text="item.name"></view>
					</view>
				</view>
					
				<!-- 收入 -->
				<view v-show="!recordType" class="grid col-4 text-center">
					<view v-for="(item, index) in income_icons"
						  @click="record(item.id, item.name, $event)"
						  :class="curSelectItemId == item.id ? 'jump-animation':''" >
						<view class="cu-avatar round margin-top-xl" 
							  :class="curSelectItemId == item.id ? 'select-icon':''"
							  style="background-color: #FFFFFF !important"
							  :style="'background-image: url(' + base64_header + item.path + ')'">
						</view>
						<view class="text-sm" v-text="item.name"></view>
					</view>
				</view>
			</scroll-view>
			
			<!-- 输入栏 -->
			<view v-show="inputShow" class="margin-tb-lg" style="height: 551.25rpx;">
				<view class="input-box">
					<view class="diplay-content align-center padding">
						<text class="cuIcon-refund"></text>
						<view style="width: 100rpx; font-size: 12px;" v-text="recordType ? '支出' : '收入'"></view>
						<input style="width: 200rpx;" v-model="recordMoney" maxlength="8" type="text" disabled>
					</view>
					<view class="diplay-content align-center padding">
						<text class="cuIcon-edit"></text>
						<view style="width: 100rpx; font-size: 12px;">备注</view>
						<input style="width: 450rpx; font-size: 14px;" v-model="recordMark" type="text" maxlength="30" placeholder="更具体的描述?">
					</view>
					<view class="grid col-4 text-center">
						<view class="solid padding-sm" @click="inputNumber('7')">7</view>
						<view class="solid padding-sm" @click="inputNumber('8')">8</view>
						<view class="solid padding-sm" @click="inputNumber('9')">9</view>
						<view class="solid padding-sm">
							<picker mode="date" @change="changeRecordDate" style="font-size: 27rpx" :end="display.dateEndRange" v-text="display.recordDateShow"></picker>
						</view>
						<view class="solid padding-sm" @click="inputNumber('4')">4</view>
						<view class="solid padding-sm" @click="inputNumber('5')">5</view>
						<view class="solid padding-sm" @click="inputNumber('6')">6</view>
						<view class="solid padding-sm" @click="inputOperation('+')">+</view>
						<view class="solid padding-sm" @click="inputNumber('1')">1</view>
						<view class="solid padding-sm" @click="inputNumber('2')">2</view>
						<view class="solid padding-sm" @click="inputNumber('3')">3</view>
						<view class="solid padding-sm" @click="inputOperation('-')">-</view>
						<view class="solid padding-sm" @click="inputDot()">.</view>
						<view class="solid padding-sm" @click="inputNumber('0')">0</view>
						<view class="solid padding-sm" @click="inputDelete()">退格</view>
						<view class="solid padding-sm" @click="submit()">完成</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {outcome_icons, income_icons, base64_header} from '../../static/icons.js'
	import {dateTransfer, dateFormat} from '../../common/dateUtils.js'
	export default {
		data() {
			return {
				op: '',					// 页面操作（update）
				ops: ['update'],
				
				userId: null,	 		// 用户ID
				bookId: null,			// 账本ID
				recordId: null,			// 账单ID
				recordType: true,		// 记账类型 true支出 | false收入  | 1支出 | 0收入
				inputShow: false,		// 输入组件是否显示
				display: {
					recordDateShow: '',		// 记账日期显示
					dateEndRange: '',		// 日期最大可选值
				},
				styleName: '',			// 类型名称
				recordMark: '',			// 备注
				recordMoney: '0',		// 记账金额
				recordDate: '',			// 记账日期
				recordTypeId: 0,		// 类型ID
				hasOperation: false,	// 输入框中是否还有运算字符
				curSelectItemId: 0,		// 当前选择的项目的ID
				curSelectItem: '', 		// 当前选择的项目
				scrollHeight: 1100,		// 滚动组件长度
				iconItems: {
					income: [],
					outcome: []
				},
				outcome_icons, income_icons, base64_header
			}
		},
		watch: {
			inputShow(oldVar, newVar) {
				this.scrollHeight = oldVar ? 480 : 1100  // 当输入框展开时，缩小scroll-view的高度
			}
		},
		onLoad(option) {
			this.op = option.op
			let nowStr = new Date().toISOString().split('T')[0]  // 输入组件上显示的日期，格式为yyyy-MM-dd
			this.display.dateEndRange = nowStr
			
			if (this.ops.indexOf(this.op) > -1) {
				this.recordId = option.recordId
				this.queryByRecordId()  // 查询信息
				return
			}
			
			this.bookId = option.book_id  // 获取账本ID
			this.userId = this.$store.state.userInfo.id  // 获取用户ID
			
			this.recordDate = dateTransfer(nowStr, '-')  // 记录保存时的日期，格式为yyyyMMdd
			this.display.recordDateShow = nowStr
			
			// 参数验证
			if (this.$anyNull(this.bookId, this.userId)) {
				uni.showToast({
					title: '加载失败',
					icon: 'error'
				})
			}
		},
		methods: {
			dateFormat,
			
			/**
			 * 加载图片路径
			 */
			loadRecordIcons() {
				this.$request({url: '/photo/icons'}).then(res => {
					this.iconItems.income = res.data.data
				})
			},
			
			/**
			 * 修改记录类型
			 * @param {Object} type 记录类型
			 */
			changeRecordType(type) {
				this.recordType = type
				this.inputShow = false
				this.curSelectItemId = 0
			},
			
			/**
			 * 记录日期
			 */
			changeRecordDate(e) {
				this.display.recordDateShow = e.detail.value
				this.recordDate = e.detail.value.replaceAll('-', '')
			},
			
			/**
			 * 输入消费数据
			 * @param {Object} item
			 */
			record(id = 0, styleName, index) {
				this.curSelectItemId = id
				this.inputShow = true	// 输入面板展示
				this.curSelectItemId = id || 0  // 更新最近选择项目
				this.styleName = styleName || '其他'
				this.recordTypeId = id
				
				this.curSelectItem = '_' + id
			},
			
			/**
			 * 使用虚拟键盘输入数字
			 */
			inputNumber(inputChar) {
				uni.vibrateShort()
				
				if (this.recordMoney == '0') {
					this.recordMoney = inputChar
				} else {
					this.recordMoney += inputChar
				}
			},
			
			/**
			 * 使用虚拟键盘输入.
			 */
			inputDot() {
				uni.vibrateShort()
				let originStr = this.recordMoney
				let strArr = originStr.indexOf('+') ? originStr.split('+') : originStr.split('-');
				let str = strArr[strArr.length - 1]
				
				if (str.indexOf('.') >= 0) {
					return
				} else {
					this.recordMoney += '.'
				}
			},
			
			/**
			 * 使用键盘输入操作符号
			 * @param {Object} inputChar
			 */
			inputOperation(inputChar) {
				uni.vibrateShort()
				
				let originStr = this.recordMoney
				let lastWord = originStr.charAt(originStr.length - 1)
				
				if (lastWord == '+' || lastWord == '+') {
					return
				}
				
				if (this.hasOperation) {
					this.calculate()
					this.recordMoney += inputChar
				} else {
					this.hasOperation = true
					this.recordMoney += inputChar
				}
			},
			
			/**
			 * 使用键盘输入退格
			 */
			inputDelete() {
				uni.vibrateShort()
				
				if (this.recordMoney.length == 0) {
					return
				}
				
				let str = this.recordMoney.toString()
				this.recordMoney = str.substring(0, str.length - 1)
				this.hasOperation = /[+|-]/.test(this.hasOperation)
			},
			
			
			/**
			 * 根据ID查询信息记录
			 */
			queryByRecordId() {
				this.$request({
					url: `/record/${this.recordId}`
				}).then(res => {
					if (res && res.data.code == 200) {
						let record = res.data.record
						this.recordType = record.recordType == '1'  // 支出|收入
						this.styleName = record.styleName  // 消费种类名称
						this.recordMark = record.recordComment  // 备注
						this.recordMoney = String(record.recordAmount)  // 金额
						this.recordDate = record.updateDate  // 记账时间
						this.curSelectItemId = record.styleId  // 图标ID
						this.inputShow = true  // 输入框显示
						this.display.recordDateShow = this.dateFormat(record.updateDate)  // 格式化日期
					}
				})
			},
			
			/**
			 * 完成
			 */
			submit() {
				uni.vibrateShort()
				this.calculate()
				
				if (this.recordMoney <= 0) {
					this.$message.info('还没有输入金额哦~')
					return
				}
				
				uni.showLoading()
				
				let isUpdate = this.ops.indexOf(this.op) > -1
				let opUrl =  '/record/'
				
				this.$request({
					url: opUrl,
					method: isUpdate ? 'PUT' : 'POST',
					data: {
						'id': this.recordId,
						'bookId': this.bookId,
						'userId': this.userId,
						'recordAmount': this.recordMoney,
						'recordComment': this.recordMark,
						'styleId': this.recordTypeId,
						'styleName': this.styleName,
						'createDate': this.recordDate,
						'updateDate': this.recordDate,
						'recordType': this.recordType ? '1' : '0'
					}
				}).then(res => {
					if (res && res.data.code === 200) {
						uni.navigateBack()
						this.$message.success(isUpdate ? '修改成功' : '添加成功')
					}
				}).finally(res => {
					uni.hideLoading()
				})
			},
			
			/**
			 * 计算
			 */
			calculate() {
				if (this.recordMoney.indexOf('+') >= 0) {
					let arr = this.recordMoney.split('+')
					this.recordMoney = (Number(arr[0]) + Number(arr[1])).toString()
				} else if (this.recordMoney.indexOf('-') >= 0) {
					let arr = this.recordMoney.split('-')
					this.recordMoney = (Number(arr[0]) - Number(arr[1])).toString()
				}
			},
			
		},
		
	}
</script>

<style>
	page {
		width: 100vw;
		height: 100vh;
	}
	
	.input-box {
		position: fixed;
		bottom: 5px;
	}
	
	.input-box view {
		background-color: #fff;
	}
	
	.diplay-content {
		display: flex;
		font-size: 16px;
		line-height: 16px;
	}
	
	.padding-sm {
		padding: 28rpx;
	}
	
	.icon {
		width: 64rpx !important;
		height: 64rpx !important;
		border-radius: 64rpx;
	}
	
	.select-icon {
		border: 1px solid #efedda;
	}
	
	.scroll-container {
		padding-bottom: 100rpx;
	}
</style>
